# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 球台模型
管理校区内的球台资源
"""

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

from app import db


class Table(db.Model):
    """
    球台模型
    管理校区内的球台资源和状态
    """
    __tablename__ = 'tables'

    # 基础字段
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    campus_id = db.Column(db.BigInteger, db.ForeignKey('campuses.id'),
                         nullable=False, comment='所属校区')
    name = db.Column(db.String(50), nullable=False, comment='球台名称/编号')

    # 状态
    status = db.Column(db.Enum('available', 'maintenance', 'disabled'),
                      nullable=False, default='available', comment='球台状态')

    # 审计字段
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.now,
                          onupdate=datetime.now, comment='更新时间')

    # 唯一约束
    __table_args__ = (
        db.UniqueConstraint('campus_id', 'name', name='unq_table_campus_name'),
    )

    # 关联关系
    campus = db.relationship('Campus')
    reservations = db.relationship('Reservation', lazy='dynamic')

    def __init__(self, **kwargs):
        super(Table, self).__init__(**kwargs)

    def is_available(self):
        """是否可用"""
        return self.status == 'available'

    def is_available_at(self, date, start_time, end_time):
        """检查指定时间段是否可用"""
        if not self.is_available():
            return False

        # 检查是否有时间冲突的预约
        from app.models.reservation import Reservation
        conflicting = Reservation.query.filter(
            Reservation.table_id == self.id,
            Reservation.reservation_date == date,
            Reservation.status.in_(['confirmed', 'pending']),
            db.or_(
                db.and_(Reservation.start_time < end_time,
                       Reservation.end_time > start_time)
            )
        ).first()

        return conflicting is None

    def get_reservations_for_date(self, date):
        """获取指定日期的预约列表"""
        return self.reservations.filter_by(reservation_date=date).order_by('start_time').all()

    def get_daily_usage_rate(self, date):
        """获取指定日期的使用率"""
        from app.config import Config
        from datetime import time

        # 解析配置中的时间字符串
        open_time_str = getattr(Config, 'DEFAULT_OPEN_TIME', '07:00:00')
        close_time_str = getattr(Config, 'DEFAULT_CLOSE_TIME', '22:00:00')

        # 转换为time对象
        open_time = time(*map(int, open_time_str.split(':')))
        close_time = time(*map(int, close_time_str.split(':')))

        # 营业时间内的总分钟数
        total_minutes = (
            datetime.combine(date, close_time) -
            datetime.combine(date, open_time)
        ).seconds // 60

        # 已预约的分钟数
        reservations = self.get_reservations_for_date(date)
        used_minutes = 0
        for reservation in reservations:
            if reservation.status in ['confirmed', 'completed']:
                duration = (
                    datetime.combine(date, reservation.end_time) -
                    datetime.combine(date, reservation.start_time)
                ).seconds // 60
                used_minutes += duration

        return (used_minutes / total_minutes * 100) if total_minutes > 0 else 0

    def get_status_display(self):
        """获取状态显示文本"""
        status_map = {
            'available': '可用',
            'maintenance': '维护中',
            'disabled': '已禁用'
        }
        return status_map.get(self.status, self.status)

    def can_reserve(self):
        """是否可以预约"""
        return self.status == 'available'

    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'campus_id': self.campus_id,
            'name': self.name,
            'status': self.status,
            'status_display': self.get_status_display(),
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'campus_name': self.campus.name if self.campus else None
        }

    def __repr__(self):
        return f'<Table {self.name} in {self.campus.name if self.campus else "Unknown"}>'